// Describe: 启动服务
package cmd

import (
	"github.com/rs/zerolog/log"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"os"
	"os/exec"
	"wormhole/core"
	"wormhole/pkg/event"
)

var startCmd = &cobra.Command{
	Use:     "start",
	Aliases: []string{"run", "listen"},
	Short:   "启动wormhole服务",
	Long:    ``,
	Run: func(cmd *cobra.Command, args []string) {
		if isDaemon {
			logPath := viper.GetString("log.path")
			f, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
			if err != nil {
				log.Err(err).Send()
			}
			log.Logger = log.Output(f)
			core.IsBaked = true
			exe := exec.Command(os.Args[0], "server", "start")
			if logPath != "" {
				stdout, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
				if err != nil {
					log.Print(os.Getpid(), ": 打开日志文件错误:", err)
				}
				exe.Stdout = stdout
				exe.Stderr = stdout
			}

			//异步启动子进程
			err = exe.Start()
			if err != nil {
				log.Fatal().Err(err).Msg("启动失败")
			}
			log.Info().Msg("启动成功")
		} else {
			core.SendSingle2Server(event.Start)
			core.Controller()
		}
	},
}

var isDaemon bool

func init() {
	serverCmd.AddCommand(startCmd)
	startCmd.Flags().BoolVarP(&isDaemon, "daemon", "d", false, "以守护进程启动")
}
